package org.jeefb.modules.sys.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.jeefb.common.PageVO;
import org.jeefb.common.ServiceResult;
import org.jeefb.common.utils.EncryptUtils;
import org.jeefb.common.utils.ExceptionUtils;
import org.jeefb.core.redis.RedisKVManager;
import org.jeefb.modules.sys.contants.SystemCachedContants;
import org.jeefb.modules.sys.contants.SystemContants;
import org.jeefb.modules.sys.dao.SysUserMapper;
import org.jeefb.modules.sys.entity.SysUser;
import org.jeefb.modules.sys.service.UserService;
import org.jeefb.modules.sys.vo.UserBaseVO;
import org.jeefb.modules.sys.vo.UserInfoVO;
import org.jeefb.modules.sys.vo.UserLoginVO;
import org.jeefb.pagehelper.PageHelper;
import org.jeefb.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

/**
 * 
 * @ClassName: UserServiceImpl
 * @Description: 用户信息管理
 * @author genemax1107@aliyun.com
 * @date 2016年5月27日 上午11:26:16
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	private static final Logger logger = Logger.getLogger(UserServiceImpl.class);
	@Autowired
	private RedisKVManager redisKVManager;
	@Autowired
	private SysUserMapper sysUserMapper;
	
	/**
	  * 
	  * @Description: 根据主键删除
	  * @param id
	  * @return    
	  * @return ServiceResult<Boolean>
	  */
	public ServiceResult<Boolean> delete(String  id){
		ServiceResult<Boolean> result = new ServiceResult<Boolean>();
		try {
 			sysUserMapper.deleteByPrimaryKey(id);
		} catch (Exception e) {
			logger.error(ExceptionUtils.printExceptionInfo(e, id));
			result.setSuccess(false);
		}
		return result;
	}
	 
	 /**
	  * 
	  * @Description: 批量删除
	  * @param ids
	  * @return    
	  * @return ServiceResult<Boolean>
	  */
	 public ServiceResult<Boolean> delete(List<String>  ids){
		 ServiceResult<Boolean> result = new ServiceResult<Boolean>();
			try {
	 			sysUserMapper.deleteBatchByIds(ids);
			} catch (Exception e) {
				logger.error(ExceptionUtils.printExceptionInfo(e, ids));
				result.setSuccess(false);
			}
			return result;
	 }
	 /**
	  * 
	  * @Description: 保存或更新
	  * @param userInfoVO
	  * @return    
	  * @return ServiceResult<Boolean>
	  */
	 public ServiceResult<Boolean> saveOrUpdate(UserInfoVO userInfoVO ){
		 ServiceResult<Boolean> result = new ServiceResult<Boolean>();
			try {
				SysUser sysUser = chanageToPO(userInfoVO);
				if(sysUser != null){
					if(sysUser.getId() != null){
						sysUserMapper.updateByPrimaryKeySelective(sysUser);
					}else {
						sysUserMapper.insertSelective(sysUser);
					}
				} else {
					result.setSuccess(false);
				}
			} catch (Exception e) {
				logger.error(ExceptionUtils.printExceptionInfo(e, userInfoVO));
				result.setSuccess(false);
			}
			return result;
	 }
	
    /**
     * 
     * @Description: 分页查询
     * @param userInfoVO
     * @param  
     * @return    
     * @return ServiceResult<PageInfo<UserInfoVO>>
     */
	public ServiceResult<PageVO<UserInfoVO>> selectPage(UserInfoVO userInfoVO ,Integer offset ,Integer pageSize) {
		ServiceResult<PageVO<UserInfoVO>> result = new ServiceResult<PageVO<UserInfoVO>>();
		try {
			PageHelper.offsetPage(offset, pageSize);
 			List<UserInfoVO> list = sysUserMapper.selectBySysUser(userInfoVO);
 			PageInfo<UserInfoVO> page = new PageInfo<UserInfoVO>(list);
 			PageVO<UserInfoVO> pageVO = new PageVO<UserInfoVO>();
 			pageVO.setOffset(offset);
 			pageVO.setRows(list);
 			pageVO.setTotal(page.getTotal());
 			result.setResult(pageVO);
		} catch (Exception e) {
			logger.error(ExceptionUtils.printExceptionInfo(e, userInfoVO));
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 
	 * @Description: 校验用户信息 并返回前端
	 * @param @param
	 *            userLoginVO
	 * @param @return
	 * @return ServiceResult<UserVO>
	 */
	public ServiceResult<UserBaseVO> login(UserLoginVO userLoginVO, String sessionId) {
		ServiceResult<UserBaseVO> result = new ServiceResult<UserBaseVO>();
		try {
			// 校验验证码
			if (!checkVerfiyCode(sessionId, userLoginVO.getVerfiyCode())) {
				result.setCode("login.verfiycode.error");
				return result;
			}
			// 校验用户与密码
			SysUser sysUser = sysUserMapper.selectByUserName(userLoginVO.getUserName());
			if (sysUser != null) {
				if (SystemContants.LOCK_STATUS.equals(sysUser.getStatus())) {
					result.setCode("login.username.lock.error");
					return result;
				}
				boolean vaileUserInfo = EncryptUtils.desCode(sysUser.getUserSalt(), userLoginVO.getPassword(),
						sysUser.getPassword());
				if (vaileUserInfo) {
					UserBaseVO userBaseVO = chanageSysUserToUserBaseVO(sysUser);
					redisKVManager.set(SystemCachedContants.ADMIN_USER_SESSION + sessionId,
							JSON.toJSONString(userBaseVO), SystemCachedContants.ADMIN_TIME_OUT, TimeUnit.MINUTES);
					result.setResult(userBaseVO);
					return result;
				}
			}
			result.setCode("login.username.password.error");
		} catch (Exception e) {
			logger.error(ExceptionUtils.printExceptionInfo(e, userLoginVO));
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 
	 * @Description: 值对象转换
	 * @param @param
	 *            sysUser
	 * @param @return
	 * @return UserBaseVO
	 */
	private UserBaseVO chanageSysUserToUserBaseVO(SysUser sysUser) {
		UserBaseVO userBaseVO = new UserBaseVO();
		userBaseVO.setEmail(sysUser.getEmail());
		userBaseVO.setId(sysUser.getId());
		userBaseVO.setPhone(sysUser.getPhone());
		userBaseVO.setRealName(sysUser.getRealName());
		userBaseVO.setUserName(sysUser.getUserName());
		return userBaseVO;
	}
	/**
	 * 
	 * @Description: 值转换
	 * @param userInfoVO
	 * @return    
	 * @return SysUser
	 */
	private static SysUser chanageToPO(UserInfoVO userInfoVO){
		if(userInfoVO !=null){
			SysUser sysUser = new SysUser();
			sysUser.setCreateBy(userInfoVO.getCreateBy());
			sysUser.setCreateDate(userInfoVO.getCreateDate());
			sysUser.setEmail(userInfoVO.getEmail());
			sysUser.setId(userInfoVO.getId());
			sysUser.setPassword(userInfoVO.getPassword());
			sysUser.setPhone(userInfoVO.getPhone());
			sysUser.setRealName(userInfoVO.getRealName());
			sysUser.setStatus(userInfoVO.getStatus());
			sysUser.setUpdateBy(userInfoVO.getUpdateBy());
			sysUser.setUpdateDate(userInfoVO.getUpdateDate());
			sysUser.setUserName(userInfoVO.getUserName());
			sysUser.setUserSalt(userInfoVO.getUserSalt());
			return sysUser;
		}
		return null;
	}

	/**
	 * 
	 * @Description: 校验验证码
	 * @param @param
	 *            sessionId
	 * @param @param
	 *            verfiyCode
	 * @param @return
	 * @return boolean
	 */
	private boolean checkVerfiyCode(String sessionId, String verfiyCode) {
		String cachedVerfiyCode = (String) redisKVManager.get(SystemCachedContants.ADMIN_VERFIY_SESSION + sessionId);
		return verfiyCode.equalsIgnoreCase(cachedVerfiyCode);
	}
	
	
	 

}
